package com.llcbenwu.controller;

import com.llcbenwu.config.Result;
import com.llcbenwu.config.SimpleResponse;
import com.llcbenwu.mode.SocialUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lilinchun
 * @date 2021/10/25 0025 17:26
 */
@RestController
@Slf4j
public class SecurityController {

    // 获取session中的内容
    private RequestCache requestCache = new HttpSessionRequestCache();

    //用户请求跳转
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    private String url = "/llc-signIn.html";

    /**
     * 当需要身份认证时，跳转到这里
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)  //返回一个401
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("当需要身份认证时，跳转到这里");
        //当需要认证的接口需要跳转，因为在SecurityConfig中配置 loginPage为登录跳转路径，为了登录之后再跳转到之前需要请求的接口，就需要从session中去拿
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest != null) {
            //需要跳转请求的url
            String redirectUrl = savedRequest.getRedirectUrl();
            log.info("引发跳转请求的是：" + redirectUrl);
            //判断redirectUrl是否是html结尾的
            if (StringUtils.endsWith(redirectUrl, ".html")) {
                redirectStrategy.sendRedirect(request, response, url);
            }
        }
        return new SimpleResponse("访问的服务需要身份认证，请引导用户到登录页");
    }

    /**
     *获取用户三方信息
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/social/user")
    public SocialUserInfo getSocialUserInfo(HttpServletRequest httpServletRequest) {
        SocialUserInfo socialUserInfo=new SocialUserInfo();
        Connection<?> connectionFromSession = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(httpServletRequest));
        socialUserInfo.setHeadimg(connectionFromSession.getImageUrl());
        socialUserInfo.setNickname(connectionFromSession.getDisplayName());
        socialUserInfo.setProviderId(connectionFromSession.getKey().getProviderId());
        socialUserInfo.setProviderUserId(connectionFromSession.getKey().getProviderUserId());
        return socialUserInfo;
    }
    /**
     *session失效的跳转的路径
     */
    @GetMapping("/session/invalid")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public Result<String>  getSocialUserInfo() {
        return new Result<>("session失效");
    }

}
